<template>
    <el-container>
        <!--侧边-->
        <el-aside width="200px">
            <div class="sidebar-logo-container">
                <img src="../assets/logo.svg" class="sidebar-logo" alt="logo" />
                <h1 class="sidebar-title">智仓通</h1>
            </div>
            <el-menu 
                :default-active="activeMenu"
                background-color="#FCFCFC"
                text-color="#333"
                active-text-color="#45B984"
                unique-opened
                @select="handleMenuSelect">
                <!--一级菜单-->
                <el-sub-menu :index="item.permission_id + ''" v-for="item in listq" :key="item.permission_id">
                    <template #title>
                        <span>{{ item.permission_name }}</span>
                    </template>

                    <!--二级菜单-->
                    <el-menu-item :index="item1.permission_address + ''" v-for="item1 in item.children" :key="item1.permission_id" @click="handleMenuClick(item1.permission_address)">
                        <span>{{ item1.permission_name }}</span>
                    </el-menu-item>
                </el-sub-menu>
            </el-menu>
        </el-aside>

        <el-container>
            <!--头部-->
            <el-header>
                <el-row>
                    <el-col :span="15">
                        <div class="grid-content">
                            <div class="menu-icon">
                                <el-icon><Menu/></el-icon>
                            </div>
                        </div>
                    </el-col>
                    <el-col :span="9">
                        <div class="grid-content">
                            <div class="header-container">
                                <!-- 消息通知 -->
                                <el-dropdown @command="goToInfoList" trigger="hover">
                                    <span style="padding-right: 50px; cursor: pointer; position: relative;">
                                        消息
                                        <el-badge :value="messageCounts.total" :hidden="messageCounts.total === 0" class="message-badge" :max="99">
                                        </el-badge>
                                    </span>
                                    <template #dropdown>
                                        <el-dropdown-menu>
                                            <el-dropdown-item 
                                                v-for="messageType in messageTypes" 
                                                :key="messageType.type"
                                                :command="messageType.type"
                                            >
                                                <div class="message-type-content">
                                                    <span>{{ messageType.label }}</span>
                                                    <el-badge 
                                                        :value="messageCounts.details[messageType.type] || 0" 
                                                        :hidden="!messageCounts.details[messageType.type]"
                                                        type="danger"
                                                        class="message-type-badge"
                                                        :max="99"
                                                    >
                                                    </el-badge>
                                                </div>
                                            </el-dropdown-item>
                                        </el-dropdown-menu>
                                    </template>
                                </el-dropdown>
                                
                                <span style="padding-right: 50px; cursor:pointer;" @click="goHome">首页</span>
                                <el-dropdown @command="handleUserMenu">
                                    <span class="el-dropdown-link header-user" style="cursor:pointer;display: flex;align-items: center;">
                                        <img :src="user.avatar" class="user-img" />
                                        <span style="margin-left: 5px;">{{user.name}}</span>
                                    </span>
                                    <template #dropdown>
                                        <el-dropdown-menu>
                                            <el-dropdown-item command="profile">
                                                <i class="el-icon-edit"></i> 个人资料
                                            </el-dropdown-item>
                                            <el-dropdown-item command="password">
                                                <i class="el-icon-lock"></i> 修改密码
                                            </el-dropdown-item>
                                            <el-dropdown-item divided command="logout">
                                                <i class="el-icon-switch-button"></i> 退出系统
                                            </el-dropdown-item>
                                        </el-dropdown-menu>
                                    </template>
                                </el-dropdown>
                            </div>
                        </div>
                    </el-col>
                </el-row>
            </el-header>

            <!--主题-->
            <el-main>
                <router-view></router-view>
            </el-main>
        </el-container>
    </el-container>
</template>

<script>
import {ref,reactive,onMounted} from 'vue'
import http from '../auth/index';
import { useRouter } from 'vue-router';//路由
import { ElMessageBox,ElNotification } from 'element-plus';//确认框
import * as signalR from '@microsoft/signalr' 
export default {
setup()
    {
        const router = useRouter();//路由
        //角色id
        const roleid=sessionStorage.getItem("roleid");
        //用户id
        const userid=sessionStorage.getItem("userid");
        //当前选中的菜单
        const activeMenu = ref('');
    

        //权限数据
        const listq = ref([]);
        //用户信息
        const user=reactive({
            id:"",
            account:"",
            password:"",
            name:"",
            sex:"",
            avatar:"",
            phone:"",
            position:"",
            department:""
        });

        //菜单点击跳转
        function handleMenuClick(path){
            router.push('/Main/' + path);
        };

        //菜单选中处理
        function handleMenuSelect(index) {
            activeMenu.value = index;
        }

        // 用户下拉菜单处理
        function handleUserMenu(command) {
            if (command === 'profile') {
                router.push('/Main/UserInfo?activeTab=userinfo');
            } else if (command === 'password') {
                router.push('/Main/UserInfo?activeTab=password');
            } else if (command === 'logout') {
                ElMessageBox.confirm('确定要退出系统吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    sessionStorage.clear();
                    router.push('/');
                }).catch(() => {
                    // 用户取消退出
                });
            }
        }

        // 首页跳转
        function goHome() {
            router.push('/Main');
        }

        //查出权限
        function Meau() {
            http.get("/Permission/GetMeau",{
                params:{
                    rid:roleid
                }
            }).then((res) => {
                listq.value = res.data;
            }).catch((err) => {
                console.log(err);
            })
        }

        //根据用户id查询出用户信息
        function GetUserById(){
            http.get("/User/GetUserById",{
                params:{
                    uid:userid
                }
            }).then(res=>{
                //赋值
                user.id=res.data.user_id;
                user.account=res.data.user_account;
                user.password=res.data.user_password;
                user.name=res.data.user_name;
                user.sex=res.data.user_sex;
                user.avatar=res.data.user_avatar;
                user.phone=res.data.user_phone;
                user.position=res.data.position_Name;
                user.department=res.data.department_Name;
                //存用户信息
                sessionStorage.setItem("user",JSON.stringify(user));
            })
        }


        // 防抖
        let resizeCount = 0;
        const observer = new ResizeObserver(() => {
            resizeCount++;
            console.log(`Resize event triggered ${resizeCount} times`);
            if (resizeCount > 10) {
                console.warn('Potential ResizeObserver loop issue detected');
            }
        });


        //库存预警
        function StockWarning(){
            http.post("/StockWarning/CheckWarning")
        }

        //到期预警
        function StockExpire(){
            http.post("/StockWarning/ExpirationWarning")
        }

        // 消息通知相关
        const messageCounts = ref({
            total: 0,
            details: {}
        });

        const messageTypes = ref([
            { type: '审核', label: '待审核' },
            { type: '入库', label: '待入库' },
            { type: '出库', label: '待出库' },
            { type: '到期提醒', label: '到期提醒' },
            { type: '库存', label: '库存预警' },
        ]);

        // 获取消息数量
        function getMessageCounts() {
            http.get("/Dashboard/GetMessageCounts")
            .then((res) => {
                messageCounts.value = res.data;
            }).catch((err) => {
                console.log(err);
            });
        }

        // 跳转到信息列表页面
        function goToInfoList(messageType = '') {
            if (messageType) {
                router.push(`/Main/Info`);
            } else {
                router.push('/Main/Info');
            }
        }



        //#region 实时信息

        let connection = null;
        //提示信息
        function inited(){
            // 检查是否已经有连接
            if (connection && connection.state === "Connected") {
                console.log("SignalR连接已存在，跳过重复连接");
                return;
            }
            
            var url = "http://localhost:5194"
            connection = new signalR.HubConnectionBuilder().withUrl(url + "/ChatHub").build();

            //1 监听来自服务器端对ReceiveMessage的调用
            connection.on("ReceiveMessage", function (user, message) {
                console.info('收到消息:', user, message);
                ElNotification({
                    title: user,
                    message: message,
                    position: 'bottom-right'
                });
            });
            
            //2 开启连接
            connection.start().then(function () {
                console.info('SignalR连接成功，连接状态:', connection.state);
            }).catch(function (err) {
                return console.error('SignalR连接失败:', err.toString());
            });
        }
        //#endregion

        //挂载
        onMounted(() => {
            inited();
            Meau();
            GetUserById();
            StockWarning();
            StockExpire();
            getMessageCounts();
            
            // 定时刷新消息数量（每30秒）
            setInterval(getMessageCounts, 3000);
        });

        return{
            listq,
            user,
            handleMenuClick,
            handleMenuSelect,
            activeMenu,
            router,
            handleUserMenu,
            goHome,
            // 消息通知相关
            messageCounts,
            messageTypes,
            goToInfoList
        }

    }
}
</script>

<style scoped>
.el-header{
    background-color: #FFFFFF;
    color: #333;
    text-align: center;
    line-height: 60px;
}
  
.el-aside {
    background-color: #FCFCFC;
    color: #333;
    text-align: center;
    line-height: initial;
}
  
.el-main {
    background-color: #F3F6F8;
    color: #333;
    text-align: center;
    height: 100vh;
}

.menu-icon {
  font-size: 20px;
  cursor: pointer;
}

.grid-content {
  border-radius: 4px;
  min-height: 60px;
  text-align: left;
}
.header-container {
  display: flex;
  align-items: center; 
  float:right;
}

/* 头像 */
.user-img {
  width: 50px;
  height: 50px; 
  border-radius: 50px;  
}

/* 菜单选中样式 */
.el-menu-item.is-active {
  background-color: #e8f5e8 !important;
  border-right: 3px solid #45B984 !important;
}

.el-menu-item:hover {
  background-color: #f0f9f0 !important;
}

.el-sub-menu__title:hover {
  background-color: #f0f9f0 !important;
}

/* 消息通知样式 */
.message-badge {
    position: absolute;
    top: -8px;
}

.message-type-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
}

.message-type-badge {
    margin-left: 10px;
}

.sidebar-logo-container {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 10px 0;
    height: 60px;
}

.sidebar-logo {
    width: 32px;
    height: 32px;
    margin-right: 12px;
}

.sidebar-title {
    margin: 0;
    color: #45B984;
    font-weight: 600;
    font-size: 20px;
    white-space: nowrap;
}
</style>
